var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer'); 
//启用bodyParser和接收post参数等
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data
//
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
    res.send('<h1>Welcome Realtime Server</h1>');
});


//首先做一个 options 的请求返回CORS的头信息。
app.options('/push', function(req, res){
    res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
    res.setHeader('Access-Control-Allow-Credentials', true);
    res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
});

//推送信息的接口
app.get('/push', function(req, res){
    res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
    res.setHeader('Access-Control-Allow-Credentials', true);
    var uid = req.param('uid');
    var message = req.param('message');
    var action = req.param('action');
    var token = req.param('token');
    var content = {
        message : message,
        action : action
    }
    //
    if(token === "ZRa3KaxcsXCpKxRG"){
        io.to(uid).emit("message",content);
    }
    res.send('success');
});

io.on('connection', function(socket){
    console.log('a user connected');

    //监听新用户加入
    socket.on('login', function(obj){
        //将新加入用户的唯一标识当作socket的名称，后面退出的时候会用到
        socket.name = obj.userid;
        socket.unique_id = obj.userid+'-'+new Date().getTime();
        socket.join(obj.userid);//将当前的用户加入用户的房间
        //
        console.log(socket.unique_id+'加入了聊天室');
    });

    //监听用户退出
    socket.on('disconnect', function(){
        //将退出的用户从在线列表中删除
        socket.leave(socket.name);
        console.log(socket.unique_id+'退出了聊天室');
    });

});

http.listen(3000, function(){
    console.log('listening on *:3000');
});